<template>
  <div>
    <label for="requiredMessage">Question：</label>
    <input id="requiredMessage" v-model="requiredMessage" placeholder="输入您的问题"/>
    <button @click="closeSse">关闭连接</button>
    <button @click="send">发送</button>
    <div id="title-message" class="white-wrap">{{ titleMessage }}</div>
    <div id="message" class="white-wrap">{{ message }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      source: null,
      userId: new Date().getTime(),
      requiredMessage: "",
      titleMessage: "",
      message: "",
    };
  },
  methods: {
    send() {
      let requiredMessage = this.requiredMessage;
      console.log(requiredMessage);
      this.source = new EventSource(
          'http://localhost:8080/treasure/test/sse/connect/' +
          this.userId +
          '/' +
          requiredMessage
      );

      this.source.addEventListener(
          'open',
          (event) => {
            this.titleMessage = '建立连接...\n';
            this.titleMessage += '---会话开始---\n';
            this.titleMessage += requiredMessage + '\n';
          },
          false
      );

      this.source.addEventListener(
          'message',
          (event) => {
            let parseObject = JSON.parse(event.data);
            let data = parseObject.data;
            if (data.indexOf('SSE-END') !== -1) {
              this.closeSse();
              this.addMessageInnerHTML('\n');
              this.addMessageInnerHTML('---会话完成---');
              return;
            }
            this.setMessageInnerHTML(data);
          },
          false
      );

      this.source.addEventListener(
          'error',
          (event) => {
            if (event.readyState === EventSource.CLOSED) {
              this.setMessageInnerHTML("连接关闭");
            } else {
              console.log(event);
            }
          },
          false
      );
    },

    closeSse() {
      this.source.close();
      const httpRequest = new XMLHttpRequest();
      httpRequest.open(
          'GET',
          'http://localhost:8080/treasure/test/sse/close/' + this.userId,
          true
      );
      httpRequest.send();
      console.log("close");
    },

    setMessageInnerHTML(innerHTML) {
      this.message = innerHTML;
    },

    addMessageInnerHTML(innerHTML) {
      this.message += innerHTML + '\n';
    },
  },
};
</script>
<style>
.white-wrap {
  white-space: pre-wrap;
}
button{
  margin-left: 3px;
}
</style>
